package rrrmai.activity;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.LoaderManager;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.MutableLiveData;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProvider;
import android.arch.lifecycle.ViewModelProviders;
import android.arch.persistence.room.Room;
import android.content.ContentResolver;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.databinding.DataBindingUtil;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.elvishew.xlog.XLog;
import com.jakewharton.rxbinding2.support.design.widget.RxBottomNavigationView;
import com.jakewharton.rxbinding2.support.v7.widget.RxToolbar;
import com.xgggh.rrrmai.R;
import com.xgggh.rrrmai.databinding.ActivityMainBinding;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import io.reactivex.Flowable;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subscribers.DisposableSubscriber;
import me.drakeet.multitype.ClassLinker;
import me.drakeet.multitype.ItemViewBinder;
import me.drakeet.multitype.Linker;
import rrrmai.listener.RecyclerViewItemClickListener;
import rrrmai.listener.RecyclerViewItemLongClickListener;
import rrrmai.model.PostType;
import rrrmai.model.User;
import rrrmai.repository.PostRepository;
import rrrmai.room.database.AppDataBase;
import rrrmai.service.PostService;
import rrrmai.utils.BottomNavigationViewHelper;
import rrrmai.viewbinder.Comment;
import rrrmai.viewbinder.CommentViewBinder;
import rrrmai.viewbinder.Contact;
import rrrmai.viewbinder.ContactEmpty;
import rrrmai.viewbinder.ContactEmptyViewBinder;
import rrrmai.viewbinder.ContactViewBinder;
import rrrmai.viewbinder.Home;
import rrrmai.viewbinder.HomeViewBinder;
import rrrmai.viewbinder.Post;
import rrrmai.viewbinder.PostAdsViewBinder;
import rrrmai.viewbinder.PostViewBinder;
import rrrmai.viewmodel.ContactViewModel;
import rrrmai.viewmodel.PostsViewModel;
import xgggh.activity.BaseActivity;

import static android.Manifest.permission.READ_CONTACTS;

/**
 * post  contact  edit home
 */
public class MainActivity extends BaseActivity  implements  android.support.v4.app.LoaderManager.LoaderCallbacks<Cursor> , RecyclerViewItemClickListener,RecyclerViewItemLongClickListener {
    ActivityMainBinding mBinding;
    Home mHome  = new Home();
    List<Contact> mContacts  =new ArrayList<>();
    //不看这个人的，不再这一条
    List<Post> mPosts  =new ArrayList<>();
    @IdRes int itemId=R.id.navigation_post;
    Comment mComment = new Comment();
    //https://medium.com/@dpreussler/add-the-new-viewmodel-to-your-mvvm-36bfea86b159
    PostsViewModel mPostsViewModel;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        setSupportActionBar(mBinding.toolbar);
        data();
        bind();
        listen();
    }

    private void query(){

    }

    private void data(){
        query();
        mPostsViewModel=getPostViewModelProvider();
        //mPostsViewModel.init(new PostRepository(getAPIService(),getAppDataBase()));
        mPostsViewModel.getPostList(1,18)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(bindToLifecycle())
                .subscribe(new DisposableSubscriber<List<Post>>() {
                    @Override
                    public void onNext(List<Post> posts) {
                        //mPosts.clear();
                        mPosts.addAll(posts);
                        if (itemId==R.id.navigation_post){//del insert query
                            //items.clear();
                            items.addAll(mPosts);
                            multiTypeAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        t.printStackTrace();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void bind(){
        BottomNavigationViewHelper.disableShiftMode(mBinding.navigation);

        multiTypeAdapter.register(Home.class,new HomeViewBinder());
        multiTypeAdapter.register(Comment.class,new CommentViewBinder());
        multiTypeAdapter.register(Contact.class,new ContactViewBinder());
        multiTypeAdapter.register(ContactEmpty.class,new ContactEmptyViewBinder());

        multiTypeAdapter.register(Post.class)
                .to(
                new PostViewBinder(this,this),
                new PostAdsViewBinder()
        ).withClassLinker(new ClassLinker<Post>() {
            @NonNull
            @Override
            public Class<? extends ItemViewBinder<Post, ?>> index(@NonNull Post post) {
                String type=post.getType();
                if (PostType.Ads.equals(type)){
                    return PostAdsViewBinder.class;
                }
                return PostViewBinder.class;
            }
        });
        //init
        multiTypeAdapter.setItems(items);
        mBinding.container.setAdapter(multiTypeAdapter);
    }

    private void listen(){

        RxToolbar.itemClicks(mBinding.toolbar)
                .observeOn(AndroidSchedulers.mainThread())
                .compose(bindToLifecycle())
                .subscribe(menuItem -> {
                    itemId=menuItem.getItemId();
                        switch (itemId){
                            case R.id.action_search:
                                actionSearch();
                                break;
                            case R.id.action_send:
                                //actionSend();
                                break;
                            case R.id.action_contact:
                                actionContact();
                                break;
                        }
                });
        //setSelectedItemId
        //mBinding.navigation.getMenu().getItem()
        RxBottomNavigationView.itemSelections(mBinding.navigation)
                .throttleLast(200,TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .compose(bindToLifecycle())
                .subscribe(menuItem -> {
                    items.clear();
                    mBinding.toolbar.getMenu().clear();
                    switch (menuItem.getItemId()) {
                        case R.id.navigation_post:
                            if (mPosts!=null){
                                items.addAll(mPosts);
                            }
                            mBinding.toolbar.inflateMenu(R.menu.menu_search);
                            break;
                        case R.id.navigation_contact:
                            mBinding.toolbar.inflateMenu(R.menu.menu_contact);
                            if (mContacts!=null && mContacts.size()!=0){
                                items.addAll(mContacts);
                            }else {
                                items.add(new ContactEmpty());
                            }
                            break ;
                        case R.id.navigation_comment:
                            mBinding.toolbar.inflateMenu(R.menu.menu_send);
                            items.add(mComment);
                            break ;
                        case R.id.navigation_home:
                            items.add(mHome);
                            break ;
                    }
                    multiTypeAdapter.notifyDataSetChanged();
                });
    }

    private void actionContact(){
        startActivity(new Intent(this,FollowActivity.class));
    }

    private void actionSearch(){
        Toast.makeText(this, "搜索", Toast.LENGTH_SHORT).show();
    }



    public void homeCommentClick(View view){
        Intent intent =new Intent(this,PostActivity.class);
        startActivity(intent);
    }


    public void homeConnectionClick(View view){
        Intent intent =new Intent(this,MyDataActivity.class);
        startActivity(intent);
    }




    @Override
    protected void onStart() {
        super.onStart();
      /*  RxSharedPreferences ddddd=getmRxSharedPreferences();
        ViewModelProvider viewModelProvider= getViewModelProvider();
        PostsViewModel mPostsViewModel=viewModelProvider.get(PostsViewModel.class);
        mPostsViewModel.getPostList().observe(this, new Observer<List<Post>>() {
            @Override
            public void onChanged(@Nullable List<Post> post) {
                mPosts.postValue(post);
                multiTypeAdapter.notifyDataSetChanged();
            }
        });*/
    }

    @Override
    public void OnItemClick(View view) {
        Object tag= view.getTag();
        if (tag!=null && tag instanceof Post){
            Post post= (Post) tag;
            Intent intent = new Intent(this,DetailsActivity.class);
            intent.putExtra("id",post.getId());
            startActivity(intent);
        }
    }

    @Override
    public void OnItemLongClick(View view) {
        Object tag= view.getTag();
        if (tag!=null && tag instanceof Post){
            Post post= (Post) tag;
            delDialog(post.getId());
        }
    }



    private void delDialog(String id){
        new AlertDialog.Builder(this)
                .setTitle("确认")
                .setMessage("确认屏蔽这条内容？")
                .setPositiveButton("ok", (dialog, which) -> {
                    delPost(id);
                    dialog.dismiss();
                })
                .setNegativeButton("cancel",(dialog, which) -> {
                    dialog.dismiss();
                })
                .setCancelable(true)
                .setOnDismissListener(null)
                .setOnCancelListener(null)
                .create()
                .show();
    }

    private void delPost(String id){
        Post post= new Post();
        post.setId(id);
        Observable.just(post)
                .observeOn(Schedulers.io())
                .subscribe(new Consumer<Post>() {
                    @Override
                    public void accept(Post post) throws Exception {
                        int rows=mPostsViewModel.delete(post);
                        Log.e("---","rows="+rows);
                    }
                });
        //mPosts.remove(post);
       // multiTypeAdapter.notifyDataSetChanged();
    }

    private void populateAutoComplete() {
        if (!mayRequestContacts()) {
            return;
        }
        getSupportLoaderManager().initLoader(0, null, this);
    }


    public void contactsAddClick(View view){
        populateAutoComplete();
    }

    private boolean mayRequestContacts() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }
        if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
            return true;
        }
        if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
            Snackbar.make(mBinding.getRoot().findViewById(R.id.contactsAddClick), R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE)
                    .setAction(android.R.string.ok, new View.OnClickListener() {
                        @Override
                        @TargetApi(Build.VERSION_CODES.M)
                        public void onClick(View v) {
                            requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
                        }
                    });
        } else {
            requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
        }
        return false;
    }

    /**
            * Callback received when a permissions request has been completed.
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        if (requestCode == REQUEST_READ_CONTACTS) {
            if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                populateAutoComplete();
            }
        }
    }

    @Override
    public android.support.v4.content.Loader<Cursor> onCreateLoader(int i, Bundle args) {
        Uri uri;
        String filter = args != null ? args.getString("filter") : null;
        if(filter != null){
            //根据用户指定的filter过滤显示
            uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_FILTER_URI, Uri.encode(filter));
        }else{
            //显示全部
            uri = ContactsContract.Contacts.CONTENT_URI;
        }

        String selection = "((" + ContactsContract.Contacts.DISPLAY_NAME + " NOTNULL) AND "+
                "(" + ContactsContract.Contacts.HAS_PHONE_NUMBER + " =1) AND "+
                "(" + ContactsContract.Contacts.DISPLAY_NAME + " != ''))";

        String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";

        return new android.support.v4.content.CursorLoader(this, uri, ProfileQuery.PROJECTION, selection, null, sortOrder);
    }

    @Override
    public void onLoadFinished(android.support.v4.content.Loader<Cursor> loader, Cursor cursor) {
        List<Contact> contacts = new ArrayList<>();
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            Contact contact = new Contact();
            String id=cursor.getString(ProfileQuery.ID);
            String name=cursor.getString(ProfileQuery.DISPLAY_NAME);
            contact.setName(name);

            Cursor phone =  getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + id,
                    null,
                    null);
            while (phone.moveToNext()) {
                String usernumber = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                contact.setMobile(usernumber);
            }
            contacts.add(contact);
            cursor.moveToNext();
        }
        storeLocal(contacts);
    }



    private void storeLocal(final List<Contact> contacts){
        notify(contacts);
                Flowable
                .fromCallable(() ->getContactViewModelProvider()
                        .insert(contacts))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DisposableSubscriber<Long[]>() {
                    @Override
                    public void onNext(Long[] longs) {
                        Toast.makeText(MainActivity.this, "本地加载成功", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onError(Throwable t) {
                        t.printStackTrace();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    private void  notify(List<Contact> contacts){
        items.clear();
        mContacts.clear();
        mContacts.addAll(contacts);
        items.addAll(mContacts);
        multiTypeAdapter.notifyDataSetChanged();
    }



    @Override
    public void onLoaderReset(android.support.v4.content.Loader<Cursor> loader) {

    }

    private interface ProfileQuery {

         String[] PROJECTION = new String[]{
                 ContactsContract.Contacts._ID,
                 ContactsContract.Contacts.DISPLAY_NAME,
         };

        int ID = 0;
        int DISPLAY_NAME = 1;
    }


}
